<?php
if (! defined ( 'BASEPATH' ))
    exit ( 'No direct script access allowed' );

class RekRincian extends Controller {
    public function __construct() {
        parent::__construct ();
        $this->_data = array ();
        $this->load->model ( 'rekrincian_model' );
        isController('akuntansi','rekRincian');
    }
    protected function _view($template, $data = array(), $result = false) {
        if ($data && is_array ( $data )) {
            return $this->load->view ( $template, $data, $result );
        }
        return $this->load->view ( $template, $this->_data, $result );
    }
    public function index() {
        redirect ( 'akuntansi/rekRincian/view' );
    }
    protected function _executeView() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'action' ) );
        // delete action
        if (isAccess('akuntansi','rekrincian','delete') && $array ['action'] == 'delete' && $array ['id']) {
            if ($this->rekrincian_model->delete($array['id'])) {
                $this->_data['errorMessage'] =  'Berhasil Delete Rekening Tipe' ;
                $this->_data['isSuccess'] =  true ;
            } else {
                $this->_data['errorMessage'] =  'Gagal Delete Rekening Tipe' ;
            }
        }
    }
    public function view() {
    	if (! isAccess ( 'akuntansi', 'rekrincian', 'view'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'tipe', 'action', 'page' ) );
        $this->_executeView ();
        $array['page'] = (int) $array['page'];

        //List Rek Tipe
        $this->load->model('rektipe_model');
        $listTipe = $this->config->item('listRekTipe');
        
        $listRekTipe = array();
        if($listTipe) foreach($listTipe as $tipe) {
        	$listRek[$tipe] = $this->rektipe_model->getList (100, 0, array('rekTipe'=>$tipe));

        	if($listRek[$tipe]) foreach($listRek[$tipe] as $k=>$v) {
        		$listRekTipe[$tipe][$v['rekTipeId']] = $v['rekTipeNama'];
        	}
        }
        $this->_data['listRekTipe'] = $listRekTipe;
        
        //Uri
        $array['tipe'] = !empty($array['tipe']) ? $array['tipe'] : 'all';
        
        //Where
        $where = array();
        $where['rekPeriodeTahun'] = date('Y');
        $where['rekPeriodeBulan'] = substr( '0'.date('m'), -2);
        
        if( !empty($array['tipe']) && $array['tipe'] != 'all' )
        	$where['rekTipeId'] = $array['tipe'];
        
        $total = $this->rekrincian_model->getCount($where);
        if (($array['page'] + 1) > $total)
            $array['page'] = 0;
            
        $this->load->library('pagination');    
        $limit = $this->config->item('klinik_limit');
        $config = $this->config->item('paging');
        $config['base_url'] = site_url('akuntansi/rekRincian/view/tipe/'.$array['tipe'].'/page/');
        $config['uri_segment'] = 6;
        $config['total_rows'] = $total;
        $config['per_page'] = $limit;
        
        $this->pagination->initialize($config);
        $this->_data['paging'] =  $this->pagination->create_links();
        
        $dataView = $this->rekrincian_model->getList($limit, $array['page'], $where);	
        $this->_data['dataView'] = $dataView;

        $this->_data['uri_to_assoc'] = $array;
        $this->_view ( 'akuntansi/rekRincianView' );
    }
    protected function _executeAdd() {
        $array = $this->uri->uri_to_assoc ( 3, array ('kode', 'action' ) );
        
        if ($this->input->post ( 'submit' ) == 'Simpan' && $this->input->post ( 'kirim' ) == 'kirim') {
        	$rekRealisasi = $this->input->post ( 'rekRealisasi' );
        	$rekAnggaran = $this->input->post ( 'rekAnggaran' );
        	//$rekSelisih = $this->input->post ( 'rekSelisih' );
        	//$rekProsentase = $this->input->post ( 'rekProsentase' );

            $errors = array ();
            if (empty ( $rekRealisasi ))
                $errors [] = 'Input Realisasi';    
            if (empty ( $rekAnggaran ))
                $errors [] = 'Input Anggaran';    
                
            if ($errors) {
                $this->_data['errorMessage'] =  implode ( '<br />', $errors ) ;
            } else {
            	$this->load->model('rekening_model');
            	
            	if($rekRealisasi) foreach($rekRealisasi as $rekid=>$realisasi) {
            		//Insert to RekHistory
            		$this->rekrincian_model->insertHistory($rekid);
            		
            		//Remove from RekRincian 
            		$this->rekrincian_model->delete($rekid);
            		
            		//Insert as RekRincian
            		$data[$rekid] = array ();
	            	$data[$rekid]['rekeningId'] = $rekid;
	            	$data[$rekid]['rekPeriodeTahun'] = date('Y');
	            	$data[$rekid]['rekPeriodeBulan'] = substr( '0'.date('m'), -2);
	            	
	            	$data[$rekid]['rekRealisasi'] = str_replace(',', '', $realisasi);
	            	$data[$rekid]['rekAnggaran'] = isset($rekAnggaran[$rekid]) ? $rekRealisasi = str_replace(',', '', $rekAnggaran[$rekid]) : 0;
	            	//$data[$rekid]['rekSelisih'] = isset($rekSelisih[$rekid]) ? $rekRealisasi = str_replace(',', '', $rekSelisih[$rekid]) : 0;
	            	//$data[$rekid]['rekProsentase'] = isset($rekProsentase[$rekid]) ? str_replace(',', '', $rekProsentase[$rekid]) : 0;
	            	
	            	$getDetail[$rekid] = $this->rekening_model->get($rekid);
	            	
	            	$data[$rekid]['rekSelisih'] = 0;
	            	$data[$rekid]['rekProsentase'] = 0;
	            	
	            	//Pendapatan
	            	if( get_data($getDetail[$rekid],'rekTipe') == 'Pendapatan' ) {
		            	$data[$rekid]['rekSelisih'] = $data[$rekid]['rekRealisasi'] - $data[$rekid]['rekAnggaran'];
		            	if($data[$rekid]['rekAnggaran'] > 0) {
		            		
		            		//Defisit
		            		if( $data[$rekid]['rekSelisih'] < 0 ) {
		            			$rekSelisih[$rekid] = $data[$rekid]['rekSelisih'] * -1;
		            			$data[$rekid]['rekProsentase'] = round($rekSelisih[$rekid] / $data[$rekid]['rekAnggaran'] * 100);	
		            			$data[$rekid]['rekProsentase'] = $data[$rekid]['rekProsentase'] * -1;

		            		//Surplus
		            		} else {
		            			$data[$rekid]['rekProsentase'] = round($data[$rekid]['rekSelisih'] / $data[$rekid]['rekAnggaran'] * 100);	
		            		}
		            		
		            	}
		            	
		            //Beban		
	            	} elseif( get_data($getDetail[$rekid],'rekTipe') == 'Beban' ) {
	            		$data[$rekid]['rekSelisih'] = $data[$rekid]['rekAnggaran'] - $data[$rekid]['rekRealisasi'];
		            	if($data[$rekid]['rekAnggaran'] > 0) {
		            		
		            		//Defisit
		            		if( $data[$rekid]['rekSelisih'] < 0 ) {
		            			$rekSelisih[$rekid] = $data[$rekid]['rekSelisih'] * -1;
		            			$data[$rekid]['rekProsentase'] = round($rekSelisih[$rekid] / $data[$rekid]['rekAnggaran'] * 100);	
		            			$data[$rekid]['rekProsentase'] = $data[$rekid]['rekProsentase'] * -1;

		            		//Surplus
		            		} else {
		            			$data[$rekid]['rekProsentase'] = round($data[$rekid]['rekSelisih'] / $data[$rekid]['rekAnggaran'] * 100);	
		            		}
		            		
		            	}	
	            	}

            		$this->rekrincian_model->add ( $data[$rekid] );
            	}
            	
                $this->_data['errorMessage'] =  'Berhasil Tambah Rincian Rekening Periode Baru' ;
                $_POST = array();
                $this->_data['isSuccess'] =  true ;
            } 
        
        }
    }

    public function add() {
    	if (! isAccess ( 'akuntansi', 'rekrincian', 'add'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('action' ) );
 
        //Check
        $monthNow = substr( '0'.date('m'), -2);
        $yearNow = date('Y');
            
        $where = array();
        $where['rekPeriodeBulan'] = $monthNow;
        $where['rekPeriodeTahun'] = $yearNow;
        $getDetail = $this->rekrincian_model->getDetail($where);
        if( $getDetail ) { 
        	$this->_data['notification'] = 'Periode Tahun : '.$yearNow.' & Bulan : '.monthName($monthNow).' Telah Memiliki Data. Mohon Tunggu Hingga Periode Selanjutnya';
            $this->_data['isSuccess'] =  true ;
            
        } else {
	    	$getLast = $this->rekrincian_model->getDetail();
	        if( $getLast ) { 
	            $monthLast = get_data($getLast,'rekPeriodeBulan');
	            $yearLast = get_data($getLast,'rekPeriodeTahun');
	            if( isset($monthLast) && isset($yearLast) ) {
	            	if( $yearLast > $yearNow ) {
	            		$this->_data['notification'] =  'Setting Periode Minimal Tahun : '.$yearLast;
	            		$this->_data['isSuccess'] =  true ;
	            	} elseif( $monthLast > $monthNow ) {
	            		$this->_data['notification'] =  'Setting Periode Minimal '.monthName($monthLast).' '.$yearLast; 
	            		$this->_data['isSuccess'] =  true ;
	            	}
	            }
            }
        }
        
        $this->load->model('rekening_model');
        $listRekening = $this->rekening_model->getList(100, 0);
		$this->_data['listRekening'] = $listRekening;
        
        $this->_executeAdd ();
        $this->_view ( 'akuntansi/rekRincianAdd' );
    }

    protected function _executeEdit() {
        $array = $this->uri->uri_to_assoc ( 3, array ('id', 'action' ) );
        
        if ($this->input->post ( 'submit' ) == 'Simpan' && $this->input->post ( 'kirim' ) == 'kirim') {
            $rekRealisasi = trim ( $this->input->post ( 'rekRealisasi' ) );
            $rekRealisasi = str_replace(',', '', $rekRealisasi);
            
        	$rekAnggaran = trim ( $this->input->post ( 'rekAnggaran' ) );
        	$rekAnggaran = str_replace(',', '', $rekAnggaran);
        	
//        	$rekSelisih = trim ( $this->input->post ( 'rekSelisih' ) );
//        	$rekSelisih = str_replace(',', '', $rekSelisih);
//        	
//        	$rekProsentase = trim ( $this->input->post ( 'rekProsentase' ) );
//			$rekProsentase = str_replace(',', '', $rekProsentase);
			
            $data = array ();
            $data ['rekRealisasi'] = $rekRealisasi;
            $data ['rekAnggaran'] = $rekAnggaran;
//            $data ['rekSelisih'] = $rekSelisih;
//            $data ['rekProsentase'] = $rekProsentase;

            $errors = array ();
            if (!isset ( $rekRealisasi ))
                $errors [] = 'Input Nilai Realisasi';
            if (!isset ( $rekAnggaran ))
                $errors [] = 'Input Nilai Anggaran';
//            if (!isset ( $rekSelisih ))
//                $errors [] = 'Input Nilai Selisih';
//            if (!isset ( $rekProsentase ))
//                $errors [] = 'Input Nilai Prosentase';

            if ($errors) {
                $this->_data['errorMessage'] =  implode ( '<br />', $errors ) ;
            } else {
            	$this->load->model('rekening_model');
            	$getDetail = $this->rekening_model->get($array['id']);
            	
            	$data['rekSelisih'] = 0;
	            $data['rekProsentase'] = 0;
	            	
            	//Pendapatan
            	if( get_data($getDetail,'rekTipe') == 'Pendapatan' ) {
	            	$data['rekSelisih'] = $data['rekRealisasi'] - $data['rekAnggaran'];
	            	if($data['rekAnggaran'] > 0) {
	            		
	            		//Defisit
	            		if( $data['rekSelisih'] < 0 ) {
	            			$rekSelisih = $data['rekSelisih'] * -1;
	            			$data['rekProsentase'] = round($rekSelisih / $data['rekAnggaran'] * 100);	
	            			$data['rekProsentase'] = $data['rekProsentase'] * -1;

	            		//Surplus
	            		} else {
	            			$data['rekProsentase'] = round($data['rekSelisih'] / $data['rekAnggaran'] * 100);	
	            		}
	            		
	            	}
	            	
	            //Beban		
            	} elseif( get_data($getDetail,'rekTipe') == 'Beban' ) {
            		$data['rekSelisih'] = $data['rekAnggaran'] - $data['rekRealisasi'];
	            	if($data['rekAnggaran'] > 0) {
	            		
	            		//Defisit
	            		if( $data['rekSelisih'] < 0 ) {
	            			$rekSelisih = $data['rekSelisih'] * -1;
	            			$data['rekProsentase'] = round($rekSelisih / $data['rekAnggaran'] * 100);	
	            			$data['rekProsentase'] = $data['rekProsentase'] * -1;

	            		//Surplus
	            		} else {
	            			$data['rekProsentase'] = round($data['rekSelisih'] / $data['rekAnggaran'] * 100);	
	            		}
	            		
	            	}	
            	}
            	//End
            	
            	$this->rekrincian_model->update ( $array['id'], $data );
                $this->_data['errorMessage'] =  'Berhasil Edit Rincian Rekening' ;
                unset($_POST);
                $this->_data['isSuccess'] =  true ;
                
                $rekRincian = $this->rekrincian_model->get ( $array['id'] );
                $this->_data['dataEdit'] = $rekRincian;    
            }              
        }    
    }

    public function edit() {
    	if (! isAccess ( 'akuntansi', 'rekrincian', 'edit'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('id' ) );
        if (! $array ['id'])
            show_404 ();
            
        $rekRincian = $this->rekrincian_model->get ( $array ['id'] );
        $this->_data['dataEdit'] = $rekRincian;    
        if (! $rekRincian)
            show_404 ();
        
        $this->_executeEdit();
        $this->_data['uri'] = $array;
        $this->_view ( 'akuntansi/rekRincianEdit' );
    }
    
    public function exportPdf() {
    	if (! isAccess ( 'akuntansi', 'rekrincian', 'exportexcel'))
            redirect (); 
        $array = $this->uri->uri_to_assoc ( 3, array ('tipe') );
        if (! $array ['tipe'])
            show_404 ();
            
        //Data General
        $this->load->helper('inflector');
        $this->load->model('rekening_model');
        
	    $dataRek = $this->rekening_model->get($array ['tipe']);    

	    //Data
        $where = array();
        $where['rekPeriodeTahun'] = date('Y');
        $where['rekPeriodeBulan'] = substr( '0'.date('m'), -2);
        $where['rekTipeId'] = $array['tipe'];
        $dataView = $this->rekrincian_model->getList(100, 0, $where);
	    
        //Template PDF
        $content = '<page backtop="14mm" backbottom="14mm" pagegroup="new">
				    <page_header>
					<table style="width:100%;">
					    <tr>
							<td style="width:70%;">'.$this->lang->line('global_title').'</td>
							<td style="width:30%;">Rincian : '.get_data($dataRek,'rekeningNama').'</td>
					    </tr>
				        <tr>
							<td>'.$this->lang->line('global_title_cab').'</td>
							<td>Periode : '.monthName(date('m')).' '.date('Y').'</td>
					    </tr>
					    <tr>
							<td>'.$this->lang->line('global_alamat_cab').'</td>
							<td></td>
					    </tr>
					</table>
				    </page_header>
				    <page_footer>
					<table style="width: 100%;">
					    <tr>
						<td style="text-align: right">
						    Page : [[page_cu]]/[[page_nb]]
						</td>
					    </tr>
					</table>
				    </page_footer>
				</page><br />';
	
	    $content .= '<table border="1" style="width:100%;">
				    <thead style="text-align:center;height:100px;">
					<tr height="50">
					    <th style="width:5%" rowspan="2">No</th>
					    <th style="width:35%" rowspan="2">Nama Rekening</th>
					    <th style="width:15%" colspan="2">Realisasi</th>
					    <th style="width:15%" colspan="2">Anggaran</th>
					    <th style="width:15%" colspan="2">Selisih</th>
					    <th style="width:10%" colspan="2">Prosentase</th>
					</tr>
					<tr height="50" style="border:none;">					    
						<th style="width:2%">&nbsp;</th><th style="width:13%"></th>
					   	<th style="width:2%"></th><th style="width:13%"></th>
					    <th style="width:2%"></th><th style="width:13%"></th>					    
					    <th style="width:8%"></th>
						<th style="width:2%"></th>
					</tr>
				    </thead>
				    <tbody style="text-align:center;">';

	    $no=1;
	    if($dataView) foreach ($dataView as $row) {
			$content .= '<tr>
							<td>'.$no.'</td>
							<td align="left">'.$row['rekeningNama'].'</td>
							<td>Rp. </td>
							<td align="right">'.number_format($row['rekRealisasi']).'</td>
							
							<td>Rp. </td>
							<td align="right">'.number_format($row['rekAnggaran']).'</td>
							
							<td>Rp. </td>
							<td align="right">'.number_format($row['rekSelisih']).'</td>
							
							<td>'.number_format($row['rekProsentase']).'</td>

							<td>%</td>		    		    
						</tr>';
			$no++;
	    }
	   
	    $content .= '</tbody>
	                 </table>';
		
	    //Convert to PDF
	    $this->load->library('html2pdf/html2pdf');
	    $html2pdf = new HTML2PDF('L', 'A4');
	    $html2pdf->pdf->SetDisplayMode('fullpage');
	    $html2pdf->writeHTML($content, FALSE);
	    $html2pdf->Output( underscore($dataRek['rekeningNama']).'_'.monthName(date('m')).'_'.date('Y').'.pdf' );
    }
    
    
    
}